package com.fingard.dsp.bank.directbank.crbc01.util;

import org.apache.http.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class HttpDownload {

    public static final int cache = 10 * 1024;
    private static String log = "";
    private static final String root = "";

    /**
     * 根据url下载文件，文件名从response header头中获取
     *
     * @param url
     * @return
     */
    public static String download(String url) throws IOException {
        return download(url, null);
    }

    /**
     * 根据url下载文件，保存到filepath中
     *
     * @param url
     * @param filepath
     * @return
     */
    public static String download(String url, String parentPath) throws IOException {
        FileOutputStream fileout = null;
        CloseableHttpClient client = null;
        try {
            client = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = client.execute(httpget);
            if (isFile(response)) {
                String filepath = "";
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                filepath = getFilePath(response, parentPath);
                File file = new File(filepath);
                file.getParentFile().mkdirs();
                fileout = new FileOutputStream(file);
                /**
                 * 根据实际运行效果 设置缓冲区大小
                 */
                byte[] buffer = new byte[cache];
                int ch = 0;
                while ((ch = is.read(buffer)) != -1) {
                    fileout.write(buffer, 0, ch);
                }
                is.close();
                fileout.flush();
                fileout.close();
                log = "4.文件下载成功";
            } else {
                log = "4.该账号无该交易日的电子回单，无需下载";
            }

        } catch (Exception e) {
            e.printStackTrace();
            log = "4.文件下载异常" + e.getMessage();
        } finally {
            if (client != null) {
                client.close();
            }
            if (fileout != null) {
                fileout.close();
            }
        }
        return log;
    }

    private static boolean isFile(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Type");
        if (contentHeader != null) {
            HeaderElement[] values = contentHeader.getElements();
            if (values.length > 0) {
                return "application/octet-stream".equals(values[0].getName());
            }
        }
        return true;
    }

    /**
     * 获取response要下载的文件的默认路径
     *
     * @param response
     * @return
     */
    public static String getFilePath(HttpResponse response, String parentPath) {
        String filename = getFileName(response);
        if (parentPath == null) {
            parentPath = root;
        }
        if (filename == null) {
            filename = getRandomFileName();
        }
        return parentPath + File.separator + filename;
    }

    /**
     * 获取response header中Content-Disposition中的filename值
     *
     * @param response
     * @return
     */
    public static String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Disposition");
        String filename = null;
        if (contentHeader != null) {
            HeaderElement[] values = contentHeader.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("filename");
                if (param != null) {
                    try {
                        //filename = new String(param.getValue().toString().getBytes(), "utf-8");
                        //filename=URLDecoder.decode(param.getValue(),"utf-8");
                        filename = param.getValue();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return filename;
    }

    /**
     * 获取随机文件名
     *
     * @return
     */
    public static String getRandomFileName() {
        return String.valueOf(System.currentTimeMillis());
    }

    public static void outHeaders(HttpResponse response) {
        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
    }
}
